# get_data.py
import re
from DrissionPage import Chromium
from lxml import etree
import time
from decimal import Decimal, ROUND_HALF_UP
from extensions import images_url_replace
from log_config import logger

# 全局浏览器实例
_browser = None
page_path = "temp.html"


def price_replace(price):
    price = price.strip()
    price = price.replace("¥", "")
    return price


def stock_replace(my_str: str):
    re_pattern = r"\d{1,12}"
    logger.info(f"库存信息原始文本{my_str}")
    match = re.search(re_pattern, my_str)
    if match:
        return match.group(0)
    else:
        return "0"


def has_video(html_text):
    video_xpath = '//div[@class="img-list-wrapper"]/div[1]/@class'
    html_content = etree.HTML(html_text)
    video = html_content.xpath(video_xpath)
    if video:
        video_class = video[0]
        if "video" in video_class:
            return True
    return False


class PageAnalysis:
    def __init__(self):
        self.browser = Chromium()
        self.tab = self.browser.latest_tab

    def get_page(self, url, ifvisit):
        # 是否访问网址
        if ifvisit:
            self.tab.get(url)

    def get_all_page(self):
        """
        返回所有页面信息
        """
        logger.info("获取整个网页文本")
        return self.tab.html

    def get_part_html(self, xpath):
        """
        根据xpath返回部分页面信息
        """
        logger.info(f"获取xpath路径{xpath}下的信息")
        pg_content = self.tab.ele(xpath)
        return pg_content

    def get_part_htmls(self, xpath):
        """
        根据xpath返回部分页面信息
        """
        logger.info(f"获取xpath路径{xpath}下的信息")
        pg_content = self.tab.eles(xpath)
        return pg_content

    def down_data(self, url, ifvisit=True):
        # get_page(url, ifvisit)
        if ifvisit:
            logger.info(f"访问网址{url}")
            self.tab.get(url)

        company_xpath = (
            'x://div[@id="shopNavigation"]//a[contains(@class,"company-name")]/h1'
        )

        logger.info("等待公司的xpath加载")
        self.tab.wait.ele_displayed(company_xpath, timeout=10)
        logger.info("公司的xpath加载完毕，进入下一步")
        # html_content = tab.html

    def type_one(self):
        line_xpath = '//div[contains(@class, "expand-view-item")]'

        img_url_xpath = ".//img/@src"
        sku_xpath = './/span[@class="item-label"]/text()'
        price_xpath = './/span[@class="item-price-stock"]/text()'
        stock_xpath = ".//span[2]/*/text()"

        # 1. 访问网址
        # 2. 获取标题，公司名称，公司网址
        # 3. 获取SKU列
        # 4. 每列获取图片网址，名称，价格
        html_text = etree.HTML(self.tab.html)
        line_list = html_text.xpath(line_xpath)
        logger.info("用lxml获取每一行的信息")
        products_list = []
        for line in line_list:
            try:
                img_url = line.xpath(img_url_xpath)[0]
                logger.info(f"获取图片网址{img_url}")

                img_url = images_url_replace(img_url)
                logger.info(f"处理图片网址{img_url}")
            except:
                img_url = "原链接无图"
                logger.warning(img_url)

            try:
                sku = line.xpath(sku_xpath)[0]
                logger.info(f"获取sku {sku}")
            except:
                sku = ""
                logger.info("sku 为空")

            try:
                price = line.xpath(price_xpath)[0]

                price = price_replace(price)
                logger.info(f"获取到价格并处理完成:{price}")
            except:
                price = "0"

            try:
                stock = line.xpath(stock_xpath)[0]
                if stock:
                    stock_int = stock_replace(stock)
                else:
                    stock_int = 0
                logger.info(f"获取到库存并处理完成:{stock_int}")
            except:
                stock_int = 0
            temp_dict = {
                "img_url": img_url,
                "sku": sku,
                "price": price,
                "stock": stock_int,
            }
            products_list.append(temp_dict)
            logger.info(temp_dict)

        return products_list

    def type_two(self):
        """
        点击按钮，显示信息页面
        """
        button_xpath = 'x://button[contains(@class,"sku-filter-button")]'
        line_xpath = 'x://div[@id="skuSelection"]'
        div_xpath = 'x://div[@class="cart-sider v-flex h"]'
        main_images_xpath = (
            'x://div[@id="gallery"]'  # 用于获取主图区域的内容，判断是否有视频
        )
        main_img_one_xpath = (
            '//div[@class="od-gallery-list-wapper"]//ul/li[1]//img/@src'
        )
        main_img_two_xpath = (
            '//div[@class="od-gallery-list-wapper"]//ul/li[2]//img/@src'
        )

        # main_img_button_xpath = 'x://div[@class="img-list-wrapper"]/div[2]'
        # img_xpath = "x:.//img"
        # name_xpath = "x:.//span"
        # size_xpath = "x:./div/span"
        # price_xpath = "x:./span[1]"
        # stock_xpath = "x:./span[2]"

        # 后续取消注释，调试时临时注释
        main_image_content = self.get_part_html(main_images_xpath)
        main_text = main_image_content.html
        logger.info(main_image_content)
        html_content = etree.HTML(main_text)
        logger.info(html_content)
        if has_video(main_text):
            try:
                main_img = html_content.xpath(main_img_two_xpath)
                logger.info("try")
                logger.info("main_img")
                logger.info(main_img)
            except:
                pass
        else:
            main_img = html_content.xpath(main_img_one_xpath)
            logger.info("else")
            logger.info("main_img")
            logger.info(main_img)

        main_img_url = ""
        if main_img:
            main_img_url = main_img[0]
        if main_img_url:
            main_img_url = images_url_replace(main_img_url)
        logger.info("main_img_url")
        logger.info(main_img_url)
        products_list = []
        try:
            button_list = self.tab.eles(
                button_xpath
            )  # 需要用于点击，只能用 self.tab.eles
            btn_len = len(button_list)
            logger.info("按钮列表获取完成")
            logger.info(f"共有{btn_len}个按钮")
        except:
            logger.warning("未获取到按钮列表")

        else:
            for button in button_list:
                button.click()
                logger.info(f"点击按钮{button}")

                button_html = button.html
                logger.info(button_html)
                button_text, button_img = get_button_content(button_html)
                line = None
                try:
                    line = self.get_part_html(line_xpath)
                    part_text = line.html
                    logger.info("获取sku中的所有网址信息")
                    # logger.info(part_text)
                except Exception as e:
                    logger.info("sku信息为空")

                if not line:
                    continue

                new_list = []
                new_list = get_type_two_list(
                    part_text, button_text, button_img, main_img_url
                )

                logger.info(new_list)
                products_list.extend(new_list)
                # logger.info(products_list)
                logger.info("-" * 60)
                time.sleep(0.3)
        return products_list


def get_button_content(button_html):
    button_content = etree.HTML(button_html)
    button_text = button_content.xpath("//span/text()")
    button_img = button_content.xpath("//img/@src")
    if button_text:
        button_text = button_text[0]
    if button_img:
        button_img = button_img[0]
        button_img = images_url_replace(button_img)
    btn_list = [button_text, button_img]
    logger.info(btn_list)
    return btn_list


def get_type_two_list(html_text, button_text, button_img, main_img_url):
    line_xpath = '//div[@id="skuSelection"]//div[@class="expand-view-item v-flex"]'
    img_xpath = ".//img/@src"
    name_xpath = ".//span/text()"
    size_xpath = "./div/span/text()"
    price_xpath = './/span[@class="item-price-stock"]/text()'
    stock_xpath = ".//span[2]/*/text()"

    html_content = etree.HTML(html_text)
    #  {"img_url": img_url, "sku": sku, "price": price, "stock": stock}
    line_list = html_content.xpath(line_xpath)

    products_list = []
    for line in line_list:
        try:
            # img_url = line.xpath(img_xpath)
            # if img_url:
            #     img_url = img_url[0]
            #     img_url = images_url_replace(img_url)
            # else:
            #     img_url = main_img_url
            # logger.info(img_url)
            if button_img:
                img_url = button_img
            else:
                img_url = main_img_url
        except Exception as e:
            img_url = main_img_url
        name = line.xpath(name_xpath)
        if name:
            name = name[0]
        size = line.xpath(size_xpath)
        if size:
            size = size[0]
        price = line.xpath(price_xpath)
        price_str = ""
        price_int = "0"
        if price:
            price_str = price[0]
            logger.info("price")
            logger.info(price_str)
        if price_str:
            price_int = price_replace(price_str)

        stock = line.xpath(stock_xpath)
        stock_int = "0"
        if stock:
            logger.info("库存信息")
            logger.info(stock)
            stock_str = stock[0]
            if stock_str:
                stock_int = stock_replace(stock_str)

        sku = f"{button_text}+{size}"
        products_list.append(
            {"img_url": img_url, "sku": sku, "price": price_int, "stock": stock_int}
        )
    return products_list


def read_html_file(file_path="temp.html"):
    """读取HTML文件内容"""
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误：找不到文件 {file_path}")
        return None
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return None


def extract_price_text(element):
    """从价格元素中提取价格文本"""
    price_parts = element.xpath('.//div[@class="price-info currency"]/span/text()')
    return "".join(price_parts[1:])  # 跳过货币符号


def parse_quantity_text(quantity_text):
    """解析数量文本，返回最小和最大数量"""
    if not quantity_text:
        return 1, None

    # 处理"1个起批"格式
    match_single = re.match(r"(\d+)\s*个?\s*起批", quantity_text)
    if match_single:
        return int(match_single.group(1)), None

    # 处理"≥24个"格式
    match_min = re.match(r"≥\s*(\d+)\s*个?", quantity_text)
    if match_min:
        return int(match_min.group(1)), None

    # 处理"12-24个"格式
    match_range = re.match(r"(\d+)\s*-\s*(\d+)\s*个?", quantity_text)
    if match_range:
        return int(match_range.group(1)), int(match_range.group(2))

    # 默认返回
    return 1, None


def process_step_prices(step_price_div):
    """处理阶梯价格"""
    price_comps = step_price_div.xpath('.//div[@class="price-comp"]')
    price_data = []

    for comp in price_comps:
        price_text = extract_price_text(comp)
        price = Decimal(price_text).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        quantity_text = comp.xpath(".//p/span/text()")
        quantity_text = quantity_text[0] if quantity_text else ""

        min_qty, max_qty = parse_quantity_text(quantity_text)
        price_data.append({"min": min_qty, "max": max_qty, "price": price})

    # 确保每个阶梯的 max = 下一个阶梯的 min - 1
    for i in range(len(price_data) - 1):
        price_data[i]["max"] = price_data[i + 1]["min"] - 1  # 关键修改

    return price_data


def process_range_price(range_price_div):
    """处理范围价格"""
    price_comps = range_price_div.xpath('.//div[@class="price-comp"]')
    prices = []

    for comp in price_comps:
        price_text = extract_price_text(comp)
        if price_text:
            # 使用Decimal处理价格
            prices.append(
                Decimal(price_text).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            )

    if not prices:
        return []

    # 如果有多个价格，返回最高价格
    max_price = max(prices)

    # 提取起批数量
    quantity_text = range_price_div.xpath('.//p[contains(text(), "起批")]/text()')
    quantity_text = quantity_text[0].strip() if quantity_text else ""

    min_qty, _ = parse_quantity_text(quantity_text)

    return [{"min": min_qty, "max": None, "price": max_price}]


def extract_prices(html_content):
    """从HTML内容中提取价格信息"""
    if not html_content:
        return []

    tree = etree.HTML(html_content)
    all_products = []

    # 查找所有价格模块
    price_modules = tree.xpath('//div[@id="mainPrice"]')

    for module in price_modules:
        # 检查是否为阶梯价
        step_price_div = module.xpath('.//div[contains(@class, "step-price")]')

        if step_price_div:
            # 处理阶梯价
            product_prices = process_step_prices(step_price_div[0])
        else:
            # 处理非阶梯价（范围价格）
            range_price_div = module.xpath(
                './/div[@class="price-component range-price"]'
            )

            if range_price_div:
                # class_name = range_price_div[0].get("class")
                # span_ele = module.xpath('//span[@class="label-name"]')

                # print(class_name)
                # print(span_ele[0].text)
                product_prices = process_range_price(range_price_div[0])
            else:
                product_prices = []

        if product_prices:
            all_products = product_prices

    return all_products


def analysis_data(url, ifvisit=True):
    PG_instance = PageAnalysis()
    PG_instance.down_data(url, ifvisit)
    type_xpath = '//div[@id="skuSelection"]//div[@class="feature-item"]'
    # html_content = PG_instance.get_all_page()
    html_text = etree.HTML(PG_instance.get_all_page())
    type_list = html_text.xpath(type_xpath)

    company_xpath = (
        '//div[@id="shopNavigation"]//a[contains(@class,"company-name")]/h1/text()'
    )
    company_url_xpath = (
        '//div[@id="shopNavigation"]//a[contains(@class,"company-name")]/@href'
    )
    title_list = html_text.xpath("//title/text()")
    title = ""
    if title_list:
        title = title_list[0]
        title = title.strip()
    if title:
        title = title.replace(" - 阿里巴巴", "")
    company_name = html_text.xpath(company_xpath)
    company_url = html_text.xpath(company_url_xpath)
    if company_name:
        company_name = company_name[0]
    if company_url:
        company_url = company_url[0]

    if len(type_list) == 1:
        products_list = PG_instance.type_one()
    else:
        products_list = PG_instance.type_two()

    price_xpath = 'x://div[@id="mainPrice"]'
    price_html = PG_instance.get_part_html(price_xpath)
    price_data = extract_prices(price_html.html)

    my_dict = {
        "url": url,
        "title": title,
        "company_name": company_name,
        "company_url": company_url,
        "products": products_list,
        "price_data": price_data,
    }
    print(my_dict)
    return my_dict


if __name__ == "__main__":
    # url = "https://detail.1688.com/offer/800331861182.html?offerId=800331861182&spm=a260k.home2025.recommendpart.4"
    # url = "https://detail.1688.com/offer/843708233884.html?_t=1750819202560&spm=a2615.7691456.co_0_0_wangpu_score_0_0_0_0_0_0_0000_0.0"
    # url = "https://detail.1688.com/offer/903597883974.html?spm=a26352.13672862.offerlist.9.78361e62i5i3RI"  # 多按钮，多尺寸，点击
    # url = "https://detail.1688.com/offer/942033984669.html"  # 点击，无库存信息
    url = "https://detail.1688.com/offer/740128323410.html?spm=a262eq.8274978.im_chat_detail.im_send_auto_urge_buy"  # 点击，无库存信息
    # url=''
    # get_page(url)
    # 是否打开网址并爬取
    # ifvisit = True
    ifvisit = False

    # 有效的函数
    # data = analysis_data(url, ifvisit)

    # 从文件读取HTML内容
    # html_content = read_html_file()
    # formatted_prices = extract_prices(html_content)
    # print(formatted_prices)

    # print(data)

    # tab = down_data(url)
    # type_two(tab)

    # # 示例字典1
    # mydict1 = {
    #     "url": "https://detail.1688.com/offer/843708233884.html?_t=1750819202560&spm=a2615.7691456.co_0_0_wangpu_score_0_0_0_0_0_0_0000_0.0",
    #     "title": "欧美夸张复古玻璃胸针女气质优雅服装配饰高级感胸花金属饰品别针",
    #     "company_name": "义乌市唯曼饰品有限公司",
    #     "company_url": "https://ywwmsp888.1688.com/page/creditdetail.htm",
    #     "products": [
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01uzzfdF1smZkEWi0Dm_!!2146215809-0-cib.jpg",
    #             "sku": "古金、深咖+浅咖+金黄亚克力（环保袋包）",
    #             "price": "5.5",
    #             "stock": "333",
    #         },
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01TJzKuu1smZnEVtw0D_!!2146215809-0-cib.jpg",
    #             "sku": "古金、深紫+浅紫+白AB+紫色亚克力",
    #             "price": "5.5",
    #             "stock": "172",
    #         },
    #     ],
    #     "price_data": [
    #         {"min": 1, "max": 11, "price": Decimal("5.70")},
    #         {"min": 12, "max": 23, "price": Decimal("5.60")},
    #         {"min": 24, "max": None, "price": Decimal("5.50")},
    #     ],
    # }

    # # 示例字典2
    # mydict2 = {
    #     "url": "https://detail.1688.com/offer/903597883974.html?spm=a26352.13672862.offerlist.9.78361e62i5i3RI",
    #     "title": "简约立体中空相框diy摆台框架干花作品创意手工空白标本画框装饰",
    #     "company_name": "东阳市静美工艺品有限公司",
    #     "company_url": "https://shop71i962493j338.1688.com/page/creditdetail.htm",
    #     "products": [
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01xMbJ721zyDAAXbxVE_!!2200730886782-0-cib.jpg",
    #             "sku": "原木色中空3厘米【相框+底纸】+6寸摆台：内径10.2*15.2cm",
    #             "price": "2.8",
    #             "stock": "684",
    #         },
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01RpdhfO1zyDAB1zLkP_!!2200730886782-0-cib.jpg",
    #             "sku": "胡桃木色中空3厘米【相框+底纸】+7寸摆台：内径12.7*17.8cm",
    #             "price": "3.7",
    #             "stock": "497",
    #         },
    #     ],
    #     "price_data": [{"min": 3, "max": None, "price": Decimal("10.50")}],
    # }

    # mydict3 = {
    #     "url": "https://detail.1688.com/offer/942033984669.html",
    #     "title": "FRIDAY JEWELRY新款银色锆石百搭复古气质精致食指可调节开口戒指",
    #     "company_name": "义乌市川汉电子商务商行",
    #     "company_url": "https://shop91u556j127x67.1688.com/page/creditdetail.htm?offerId=760270547714",
    #     "products": [
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN015nRUph1c1MuZwSyHY_!!2215624283540-0-cib.jpg",
    #             "sku": "定制S曲线锆石【开口戒】",
    #             "price": "8.7",
    #             "stock": "9988",
    #         }
    #     ],
    #     "price_data": [
    #         {"min": 1, "max": 11, "price": Decimal("8.70")},
    #         {"min": 12, "max": 59, "price": Decimal("8.50")},
    #         {"min": 60, "max": None, "price": Decimal("8.20")},
    #     ],
    # }

    # mydict4 = {
    #     "url": "https://detail.1688.com/offer/740128323410.html?spm=a262eq.8274978.im_chat_detail.im_send_auto_urge_buy",
    #     "title": "欧美经典水滴锆石新娘婚礼配饰饰品耳环项链手链婚纱礼服套装",
    #     "company_name": "义乌市芮蔻饰品有限公司",
    #     "company_url": "https://rakolsp.1688.com/page/creditdetail.htm?offerId=740128323410",
    #     "products": [
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01fLfbv21xiyaqOOmVV_!!3582956478-0-cib.jpg",
    #             "sku": "白色3件套A+白色镀白金",
    #             "price": "72",
    #             "stock": "355",
    #         },
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01fLfbv21xiyaqOOmVV_!!3582956478-0-cib.jpg",
    #             "sku": "白色3件套A+白色镀金色",
    #             "price": "72",
    #             "stock": "454",
    #         },
    #         {
    #             "img_url": "https://cbu01.alicdn.com/img/ibank/O1CN01fLfbv21xiyaqOOmVV_!!3582956478-0-cib.jpg",
    #             "sku": "白色3件套A+白色镀玫瑰金",
    #             "price": "72",
    #             "stock": "437",
    #         },
    #     ],
    #     "price_data": [{"min": 1, "max": None, "price": Decimal("82.00")}],
    # }

    # product_list = mydict4["products"]
    # print(len(product_list))
